import pygame as pg
from .. import setup as su,tools

class Menu(tools._State):
    def __init__(self):
        tools._State.__init__(self)
        self.from_bottom = 200
        self.spacer = 70
        self.opts = ['4 Direction Movement','8 Direction Movement',
                     'Drag w/ Mouse','Quit']
        self.next_list = ["FOUR","EIGHT","DRAG"]
        self.title = self.render_font("Fixedsys500c",40,"Menu Screen",(0,255,255))
        self.title_rect = self.title.get_rect(center=(su.SCREEN_RECT.centerx,75))
        self.pre_render_options()

    def render_font(self,font,size,msg,color=(255,255,255)):
        RenderFont = pg.font.Font(su.FONTS[font],size)
        return RenderFont.render(msg,1,color)

    def pre_render_options(self):
        font_deselect = pg.font.Font(su.FONTS["impact"],25)
        font_selected = pg.font.Font(su.FONTS["impact"],40)

        rendered_msg = {"des":[],"sel":[]}
        for option in self.opts:
            d_rend = font_deselect.render(option, 1, (255,255,255))
            d_rect = d_rend.get_rect()
            s_rend = font_selected.render(option, 1, (255,0,0))
            s_rect = s_rend.get_rect()
            rendered_msg["des"].append((d_rend,d_rect))
            rendered_msg["sel"].append((s_rend,s_rect))
        self.rendered = rendered_msg

    def get_event(self,event):
        if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:
            for i,opt in enumerate(self.rendered["des"]):
                if opt[1].collidepoint(pg.mouse.get_pos()):
                    if i == len(self.next_list):
                        self.quit = True
                    else:
                        self.next = self.next_list[i]
                        self.done = True
                    break

    def update(self,Surf,keys,mouse):
        Surf.fill((50,50,150))
        Surf.blit(self.title,self.title_rect)
        for i,opt in enumerate(self.rendered["des"]):
            opt[1].center = (su.SCREEN_RECT.centerx,self.from_bottom+i*self.spacer)
            if opt[1].collidepoint(pg.mouse.get_pos()):
                rend_img,rend_rect = self.rendered["sel"][i]
                rend_rect.center = opt[1].center
                Surf.blit(rend_img,rend_rect)
            else:
                Surf.blit(opt[0],opt[1])
        self.timeout(15)

    def timeout(self,seconds):
        """Timeout and return to title screen after 15 seconds."""
        if pg.time.get_ticks()-self.start_time > seconds*1000:
            self.next = "TITLE"
            self.done = True